package com.atguigu.cloudalibaba.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author ：pkq
 * @date ：Created in 2022/2/23 16:28
 * @description：
 * @modified By：
 * @version: $
 */
@RestController
public class OrderNacosController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Resource
    private RestTemplate restTemplate;





    @Value("${service-url.nacos-provider-servername}")
    private String serverName;

    @GetMapping("/consumer/payment/nacos/{id}")
    public String paymentInfo(@PathVariable("id") Long id) {
        //方式一：最原始的方式，即显式结合 LoadBalanceClient 和 RestTemolate 来访问 RESTful 服务
        ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-payment-provider");
        String path = String.format("http://%s:%s/payment/nacos/%s",serviceInstance.getHost(),serviceInstance.getPort(),id);
        return restTemplate.getForObject(path,String.class);
        //方式二：带有负载平衡的 RestTemplate
        //return restTemplate.getForObject("http://" + serverName+"/payment/nacos/"+id,String.class);
        //方式三：FeignClient
    }
}
